package com.chenille.tools.util

import android.app.Activity
import android.app.ActivityManager
import android.app.ActivityManager.RunningAppProcessInfo
import android.app.Application
import android.content.Context
import android.content.pm.ApplicationInfo
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.content.res.Configuration
import android.database.Cursor
import android.net.ConnectivityManager
import android.net.Uri
import android.net.wifi.WifiManager
import android.os.Build
import android.os.Environment
import android.os.Process
import android.provider.MediaStore
import android.util.Log
import org.json.JSONObject
import java.io.*
import java.net.*
import java.util.*


/**
 * @Author: FALLS CHEN
 * @Date: 2020-01-19 19:19
 * EMAIL: 636e68747474403136332e636f6d
 * @Version 1.0
 */
/**
 * 设备信息的工具类
 * <p>
 * Created by Beluga_白鲸.
 */

object DeviceUtil {
    /**
     * 获取设备宽度（px）
     *
     * @param context
     * @return
     */
    fun deviceWidth(context: Context): Int {
        return context.resources.displayMetrics.widthPixels
    }

    /**
     * 获取设备高度（px）
     *
     * @param context
     * @return
     */
    fun deviceHeight(context: Context): Int {
        return context.resources.displayMetrics.heightPixels
    }

    /**
     * SD卡判断
     *
     * @return
     */
    fun isSDCardAvailable(): Boolean {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)
    }

    /**
     * 是否有网
     *
     * @param context
     * @return
     */
    fun isNetworkConnected(context: Context?): Boolean {
        if (context != null) {
            val mConnectivityManager = context
                .getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
            val mNetworkInfo = mConnectivityManager.activeNetworkInfo
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable
            }
        }
        return false
    }

    /**
     * 返回版本名字
     * 对应build.gradle中的versionName
     *
     * @param context
     * @return
     */
    fun getVersionName(context: Context): String {
        var versionName = ""
        try {
            val packageManager: PackageManager = context.packageManager
            val packInfo: PackageInfo =
                packageManager.getPackageInfo(context.packageName, 0)
            versionName = packInfo.versionName
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return versionName
    }

    /**
     * 返回版本号
     * 对应build.gradle中的versionCode
     *
     * @param context
     * @return
     */
    fun getVersionCode(context: Context): String {
        var versionCode = ""
        try {
            val packageManager: PackageManager = context.packageManager
            val packInfo: PackageInfo =
                packageManager.getPackageInfo(context.packageName, 0)
            versionCode ="v"+ packInfo.versionCode.toString()
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return versionCode
    }

    fun getPackageName(context: Context): String {
        var versionCode = ""
        try {
            val packageManager: PackageManager = context.packageManager
            val packInfo: PackageInfo =
                packageManager.getPackageInfo(context.packageName, 0)
            versionCode = packInfo.packageName.toString()
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return versionCode
    }


    /**
     * 获取手机品牌
     *
     * @return
     */
    fun getPhoneBrand(): String {
        return Build.BRAND
    }

    /**
     * 获取手机型号
     *
     * @return
     */
    fun getPhoneModel(): String {
        return Build.MODEL
    }

    /**
     * 获取手机Android API等级（22、23 ...）
     *
     * @return
     */
    fun getBuildLevel(): Int {
        return Build.VERSION.SDK_INT
    }

    /**
     * 获取手机Android 版本（4.4、5.0、5.1 ...）
     *
     * @return
     */
    fun getBuildVersion(): String {
        return Build.VERSION.RELEASE
    }

    /**
     * 获取当前App进程的id
     *
     * @return
     */
    fun getAppProcessId(): Int {
        return Process.myPid()
    }

    /**
     * 获取当前App进程的Name
     *
     * @param context
     * @param processId
     * @return
     */
    fun getAppProcessName(context: Context, processId: Int): String? {
        var processName: String? = null
        val am =
            context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        // 获取所有运行App的进程集合
        val l: List<*> = am.runningAppProcesses
        val i = l.iterator()
        val pm: PackageManager = context.getPackageManager()
        while (i.hasNext()) {
            val info = i.next() as RunningAppProcessInfo
            try {
                if (info.pid == processId) {
                    val c = pm.getApplicationLabel(
                        pm.getApplicationInfo(
                            info.processName,
                            PackageManager.GET_META_DATA
                        )
                    )
                    processName = info.processName
                    return processName
                }
            } catch (e: Exception) {
                Log.e(DeviceUtil::class.java.name, e.message, e)
            }
        }
        return processName
    }

    /**
     * 创建App文件夹
     *
     * @param appName
     * @param application
     * @return
     */
    fun createAPPFolder(appName: String?, application: Application): String {
        return createAPPFolder(appName, application, null)
    }

    /**
     * 创建App文件夹
     *
     * @param appName
     * @param application
     * @param folderName
     * @return
     */
    fun createAPPFolder(
        appName: String?,
        application: Application,
        folderName: String?
    ): String {
        var root: File = Environment.getExternalStorageDirectory()
        var folder: File
        /**
         * 如果存在SD卡
         */
        if (isSDCardAvailable() && root != null) {
            folder = File(root, appName)
            if (!folder.exists()) {
                folder.mkdirs()
            }
        } else {
            /**
             * 不存在SD卡，就放到缓存文件夹内
             */
            root = application.getCacheDir()
            folder = File(root, appName)
            if (!folder.exists()) {
                folder.mkdirs()
            }
        }
        if (folderName != null) {
            folder = File(folder, folderName)
            if (!folder.exists()) {
                folder.mkdirs()
            }
        }
        return folder.getAbsolutePath()
    }

    /**
     * 通过Uri找到File
     *
     * @param context
     * @param uri
     * @return
     */
    fun uri2File(context: Activity, uri: Uri): File {
        val file: File
        val project =
            arrayOf(MediaStore.Images.Media.DATA)
        val actualImageCursor: Cursor? =
            context.contentResolver.query(uri, project, null, null, null)
        if (actualImageCursor != null) {
            val actualImageColumnIndex: Int = actualImageCursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
            actualImageCursor.moveToFirst()
            val imgPath: String = actualImageCursor
                .getString(actualImageColumnIndex)
            file = File(imgPath)
        } else {
            file = File(uri.getPath())
        }
        actualImageCursor?.close()
        return file
    }

    /**
     * 获取AndroidManifest.xml里 的值
     *
     * @param context
     * @param name
     * @return
     */
    fun getMetaData(context: Context, name: String?): String? {
        var value: String? = null
        try {
            val appInfo: ApplicationInfo = context.packageManager
                .getApplicationInfo(context.packageName, PackageManager.GET_META_DATA)
            value = appInfo.metaData.getString(name)
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
        }
        return value
    }

    /**
     * 判断当前设备是手机还是平板，代码来自 Google I/O App for Android
     *
     * @param context
     * @return 平板返回 True，手机返回 False
     */
    fun isPad(context: Context): Boolean {
        return ((context.getResources().getConfiguration().screenLayout
                and Configuration.SCREENLAYOUT_SIZE_MASK)
                >= Configuration.SCREENLAYOUT_SIZE_LARGE)
    }

    /**
     * 获取ip（内网ip）
     * @param context
     * @return
     */
    fun getIPAddress(context: Context): String? {
        val info = (context
            .getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager).activeNetworkInfo
        if (info != null && info.isConnected) {
            if (info.type == ConnectivityManager.TYPE_MOBILE) { //当前使用2G/3G/4G网络
                try { //Enumeration<NetworkInterface> en=NetworkInterface.getNetworkInterfaces();
                    val en: Enumeration<NetworkInterface> = NetworkInterface.getNetworkInterfaces()
                    while (en.hasMoreElements()) {
                        val intf: NetworkInterface = en.nextElement()
                        val enumIpAddr: Enumeration<InetAddress> = intf.getInetAddresses()
                        while (enumIpAddr.hasMoreElements()) {
                            val inetAddress: InetAddress = enumIpAddr.nextElement()
                            if (!inetAddress.isLoopbackAddress() && inetAddress is Inet4Address) {
                                return inetAddress.getHostAddress()
                            }
                        }
                    }
                } catch (e: SocketException) {
                    e.printStackTrace()
                }
            } else if (info.type == ConnectivityManager.TYPE_WIFI) { //当前使用无线网络
                val wifiManager =
                    context.getSystemService(Context.WIFI_SERVICE) as WifiManager
                val wifiInfo = wifiManager.connectionInfo
                return intIP2StringIP(wifiInfo.ipAddress)
            }
        } else { //当前无网络连接,请在设置中打开网络
        }
        return null
    }

    /**
     * 将得到的int类型的IP转换为String类型
     *
     * @param ip
     * @return
     */
    fun intIP2StringIP(ip: Int): String {
        return (ip and 0xFF).toString() + "." +
                (ip shr 8 and 0xFF) + "." +
                (ip shr 16 and 0xFF) + "." +
                (ip shr 24 and 0xFF)
    }

    /**
     * 获取IP(外网ip、公网ip)
     */
    fun getNetIp(): String {
        var IP = ""
        try {
            val address = "http://ip.taobao.com/service/getIpInfo2.php?ip=myip"
            val url = URL(address)
            //URLConnection htpurl=url.openConnection();
            val connection: HttpURLConnection = url
                .openConnection() as HttpURLConnection
            connection.setUseCaches(false)
            connection.setRequestMethod("GET")
            connection.setRequestProperty(
                "user-agent",
                "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.7 Safari/537.36"
            ) //设置浏览器ua 保证不出现503
            if (connection.getResponseCode() === HttpURLConnection.HTTP_OK) {
                val `in`: InputStream = connection.getInputStream()
                // 将流转化为字符串
                val reader = BufferedReader(
                    InputStreamReader(`in`)
                )
                var tmpString = ""
                val retJSON = StringBuilder()
                while (reader.readLine().also({ tmpString = it }) != null) {
                    retJSON.append(tmpString + "\n")
                }
                val jsonObject = JSONObject(retJSON.toString())
                val code: String = jsonObject.getString("code")
                if (code == "0") {
                    val data: JSONObject = jsonObject.getJSONObject("data")
                    //格式：180.000.00.000(中国区上海上海电信)
//                    IP = data.getString("ip") + "(" + data.getString("country")
//                            + data.getString("area") + "区"
//                            + data.getString("region") + data.getString("city")
//                            + data.getString("isp") + ")";
//格式：180.000.00.000
                    IP = data.getString("ip")
                    Log.e("提示", "您的IP地址是：$IP")
                } else {
                    IP = ""
                    Log.e("提示", "IP接口异常，无法获取IP地址！")
                }
            } else {
                IP = ""
                Log.e("提示", "网络连接异常，无法获取IP地址！")
            }
        } catch (e: Exception) {
            IP = ""
            Log.e("提示", "获取IP地址时出现异常，异常信息是：$e")
        }
        return IP
    }

    @Throws(IOException::class)
    fun streamreader(`is`: InputStream?): String { //转换为字符
        val isr = InputStreamReader(`is`, "gbk")
        val br = BufferedReader(isr)
        val stringBuilder = StringBuilder()
        var tmp: String = br.readLine()
        while (tmp != null) {
            stringBuilder.append(tmp)
            tmp = br.readLine()
        }
        return stringBuilder.toString()
    }

}
